package com.mall.biz.weishang;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mall.client.user.AddressService;
import com.mall.client.user.UserExtendedService;
import com.mall.client.user.UserLevelService;
import com.mall.client.user.UserService;
import com.mall.constant.TypeCommOnlyKeyConstant;
import com.mall.pojo.User;
import com.mall.pojo.UserExample;
import com.mall.pojo.UserExample.Criteria;
import com.mall.query.weishang.UserQuery;
import com.mall.vo.user.UserVO;

@Service
/**
 * 合伙人biz
 * @author Administrator
 *
 */
public class DistributorBizImpl {
	@Autowired
	private UserService userService;
	@Autowired
	private UserExtendedService userExtendedService;
	@Autowired
	private UserLevelService userLevelService;
	@Autowired
	private AddressService addressService;

	public List<UserVO> getUserVOListByQuery(UserQuery userQuery) {
		List<User> userList = getUserExampleByQuery(userQuery);
		List<UserVO> userVOList = new ArrayList<>();
		UserVO userVO = null;
		for (int i = 0; i < userList.size(); i++) {
			userVO = new UserVO();
			User user = userList.get(i);
			userVO.setUser(user);
			userVO.setUserLevel(this.userLevelService.getUserLevelByLevelAndKey((int)user.getLevel(), TypeCommOnlyKeyConstant.TYPE_WEISHANGB2B));
			userVO.setAddress(this.addressService.getDefaultAddressByUserId(user.getId()));
			userVO.setUserExtended(this.userExtendedService.getUserExtendByUserId(user.getId()));
			userVOList.add(userVO);
		}
		return userVOList;
	}
	
	
	private List<User> getUserExampleByQuery(UserQuery userQuery) {
		
		UserExample example = new UserExample();
		if(userQuery.getOrderBy() != null){
			example.setOrderByClause(userQuery.getOrderBy());
		}else{
			example.setOrderByClause("gmt_create desc");
		}
		
		if(userQuery.getPage() != null){
			example.setLimit(userQuery.getPage().getLength());
			example.setStart(userQuery.getPage().getBegin());
		}
		Criteria criteria = example.createCriteria();
		if(userQuery.getKeyWord()!=null){
			criteria.andNameAndPhoneLike("%"+userQuery.getKeyWord()+"%");
		}
		if(userQuery.getLevel()!=null && userQuery.getLevel()>0){
			criteria.andLevelEqualTo(userQuery.getLevel().shortValue());
		}if(userQuery.getLevel() == null){
			criteria.andLevelGreaterThanOrEqualTo((short)1);
		}
		if(userQuery.getType() != null){
			criteria.andTypeEqualTo(userQuery.getType());
		}
		criteria.andCommOnlyKeyEqualTo(userQuery.getOnlyKey());
		List<User> userList = this.userService.getUserByExample(example);
		
		return userList;
		
	}

}
